class AIInteraction {
  constructor() {
    this.apiUrl = 'https://api.siliconflow.cn/v1/chat/completions';
    this.apiKey = 'sk-zohkmwvldpnzqmjxxtmryyknzxlilhdjfvjsqbjxncryfxbx';
    this.model = 'THUDM/GLM-4-9B-0414';
  }

  // 基础AI调用方法
  async callAI(prompt) {
    const options = {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify({
        model: this.model,
        thinking_budget: 4096,
        top_p: 0.7,
        stream: false,
        messages: [
          {
            role: "user",
            content: prompt
          }
        ]
      })
    };

    try {
      const response = await fetch(this.apiUrl, options);
      const data = await response.json();
      
      if (data.choices && data.choices.length > 0) {
        return data.choices[0].message.content;
      } else {
        throw new Error('AI未返回有效内容');
      }
    } catch (error) {
      console.error('AI调用出错:', error);
      throw error;
    }
  }

  // 流式AI调用方法
  async callAIStream(prompt, onChunkReceived) {
    const options = {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify({
        model: this.model,
        thinking_budget: 4096,
        top_p: 0.7,
        stream: true,
        messages: [
          {
            role: "user",
            content: prompt
          }
        ]
      })
    };

    try {
      const response = await fetch(this.apiUrl, options);
      
      if (!response.body) {
        throw new Error('服务器响应中没有数据流');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let buffer = '';
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || ''; // 保留不完整的行
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data === '[DONE]') {
              return;
            }
            
            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices?.[0]?.delta?.content || '';
              if (content) {
                onChunkReceived(content);
              }
            } catch (err) {
              console.warn('解析流数据时出错:', err);
            }
          }
        }
      }
      
      // 处理剩余的缓冲数据
      if (buffer.startsWith('data: ')) {
        const data = buffer.slice(6);
        if (data !== '[DONE]') {
          try {
            const parsed = JSON.parse(data);
            const content = parsed.choices?.[0]?.delta?.content || '';
            if (content) {
              onChunkReceived(content);
            }
          } catch (err) {
            console.warn('解析流数据时出错:', err);
          }
        }
      }
    } catch (error) {
      console.error('AI流式调用出错:', error);
      throw error;
    }
  }

  // 将用户自然语言指令转换为工作流
  async translateUserQuery(query, context) {
    const prompt = `你是一个肿瘤免疫数据处理专家，请将用户的自然语言指令转换为可视化工作流定义。

用户指令: ${query}

上下文信息: ${JSON.stringify(context)}

请严格按照以下JSON格式返回结果，不要包含其他内容:
{
  "nodes": [
    {
      "id": "唯一标识符",
      "type": "节点类型(upload/preprocess/dimReduction等)",
      "name": "节点显示名称",
      "position": {"x": 100, "y": 100},
      "params": {
        "参数名": "参数值"
      }
    }
  ],
  "edges": [
    {
      "from": "起始节点ID",
      "to": "目标节点ID"
    }
  ]
}

节点类型说明:
- upload: 数据上传节点
- preprocess: 数据预处理节点
- dimReduction: 降维分析节点
- visualization: 可视化节点

示例:
用户说"上传数据并进行预处理"
返回:
{
  "nodes": [
    {"id": "n1", "type": "upload", "name": "数据上传", "position": {"x": 100, "y": 100}},
    {"id": "n2", "type": "preprocess", "name": "数据预处理", "position": {"x": 300, "y": 100}, "params": {"method": "标准化"}}
  ],
  "edges": [
    {"from": "n1", "to": "n2"}
  ]
}`;

    try {
      const aiResponse = await this.callAI(prompt);
      
      // 尝试解析AI返回的JSON
      try {
        const workflow = JSON.parse(aiResponse);
        return workflow;
      } catch (parseError) {
        console.error('AI返回的不是有效的JSON格式:', aiResponse);
        throw new Error('AI返回格式错误，请重新尝试');
      }
    } catch (error) {
      console.error('翻译用户查询出错:', error);
      throw error;
    }
  }

  // 智能参数推荐
  async recommendParameters(dataInfo) {
    const prompt = `根据以下数据信息，推荐合适的分析参数:

数据信息: ${JSON.stringify(dataInfo)}

请提供推荐的参数配置和理由，按照以下格式返回:
{
  "recommendations": [
    {
      "process": "处理步骤名称",
      "parameters": {
        "参数名": "推荐值"
      },
      "reason": "推荐理由"
    }
  ]
}`;

    try {
      const aiResponse = await this.callAI(prompt);
      return JSON.parse(aiResponse);
    } catch (error) {
      console.error('参数推荐出错:', error);
      throw error;
    }
  }
}

export default new AIInteraction();